/**
 * 此文件用于在全局范围内过滤控制台输出
 * 将特定类型的日志消息完全隐藏，不会在控制台显示
 */

// 要过滤的消息模式列表
const FILTERED_PATTERNS = [
  'ResizeObserver',
  '[HMR]',
  '[webpack-dev-server]'
];

// 是否在开发环境中（只在开发环境过滤）
const isDev = process.env.NODE_ENV === 'development';

// 启用控制台过滤
export function enableConsoleFilter() {
  if (!isDev || typeof window === 'undefined') return;

  // 已经初始化过滤器，不再重复初始化
  if (window._consoleFilterInitialized) return;
  window._consoleFilterInitialized = true;
  
  // 保存原始方法
  const originalConsoleLog = console.log;
  const originalConsoleInfo = console.info;
  const originalConsoleWarn = console.warn;
  const originalConsoleError = console.error;
  
  // 创建过滤函数
  const shouldFilter = (args) => {
    if (!args || args.length === 0) return false;
    
    const firstArg = args[0];
    if (!firstArg) return false;
    
    // 检查字符串消息
    if (typeof firstArg === 'string') {
      return FILTERED_PATTERNS.some(pattern => firstArg.includes(pattern));
    }
    
    // 检查错误对象
    if (firstArg instanceof Error && firstArg.message) {
      return FILTERED_PATTERNS.some(pattern => firstArg.message.includes(pattern));
    }
    
    return false;
  };
  
  // 替换控制台方法
  console.log = function(...args) {
    if (shouldFilter(args)) return;
    originalConsoleLog.apply(console, args);
  };
  
  console.info = function(...args) {
    if (shouldFilter(args)) return;
    originalConsoleInfo.apply(console, args);
  };
  
  console.warn = function(...args) {
    if (shouldFilter(args)) return;
    originalConsoleWarn.apply(console, args);
  };
  
  console.error = function(...args) {
    if (shouldFilter(args)) return;
    originalConsoleError.apply(console, args);
  };
  
  // 记录原始方法，以便恢复
  window._originalConsoleMethods = {
    log: originalConsoleLog,
    info: originalConsoleInfo,
    warn: originalConsoleWarn,
    error: originalConsoleError
  };
}

// 禁用控制台过滤，恢复原始行为
export function disableConsoleFilter() {
  if (!isDev || typeof window === 'undefined') return;
  if (!window._consoleFilterInitialized) return;
  
  // 恢复原始方法
  const methods = window._originalConsoleMethods;
  if (methods) {
    console.log = methods.log;
    console.info = methods.info;
    console.warn = methods.warn;
    console.error = methods.error;
  }
  
  window._consoleFilterInitialized = false;
  window._originalConsoleMethods = null;
}

export default {
  enableConsoleFilter,
  disableConsoleFilter
}; 